package com.xinchuang.domain.vo.qr;

import com.xinchuang.domain.type.NormalOutQuotationaSubEnum;
import com.xinchuang.utils.BigdecimalUtil;
import com.xinchuang.utils.CheckUtil;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.List;

/**
 * 三坐标测量费
 */
@Data
public class QrCMMeasure {

    //小计
    private double subTotal;
    //数据
    private List<DataList> dataList;

    @Data
    @AllArgsConstructor
    public class DataList {
        //名称/Item
        private String itemName;
        //单价(元)/Unit Price(RMB)
        private double price;
        //工时(小时)/Hour
        private double hour;
        // 金额(元)/Price(RMB)
        private double totalPrice;
    }

    public void checkCMMMeasure() {
        BigDecimal subTotalAfter = new BigDecimal(0.00);
        String strType = NormalOutQuotationaSubEnum.DESIGN_FEE.getCn();
        for (DataList item : this.getDataList()) {
            //检验小计
            BigDecimal totalPrice = calculateTotalPrice(
                    BigdecimalUtil.double2BigDecimal2Decimal(item.getPrice()),
                    BigdecimalUtil.double2BigDecimal2Decimal(item.getHour()));
            subTotalAfter = subTotalAfter.add(totalPrice);
            //校验明细
            String type = strType + " " + item.getItemName() + " 金额";
            CheckUtil.checkIsEqual2(type,
                    BigdecimalUtil.double2BigDecimal2Decimal(item.getTotalPrice()),
                    totalPrice);
        }
        checkSubTotal(strType,
                BigdecimalUtil.double2BigDecimal2Decimal(this.getSubTotal()),
                subTotalAfter.setScale(2, RoundingMode.HALF_UP));

    }

    /**
     * 计算总价
     *
     * @param price 单价
     * @param count 工时、数量
     * @return
     */
    private BigDecimal calculateTotalPrice(BigDecimal price, BigDecimal count) {
        return price.multiply(count).setScale(2, RoundingMode.HALF_UP);
    }


    /**
     * 验证小计是否一致
     *
     * @param type 类型
     * @param subTotal 前端入参
     * @param subTotalAfter 后端计算
     */
    private void checkSubTotal(String type, BigDecimal subTotal, BigDecimal subTotalAfter) {
        if (subTotalAfter.compareTo(subTotal) != 0) {
            throw new RuntimeException(type + "-小计计算结果不一致。结果为" + subTotalAfter);
        }
    }
}
